package com.shangma.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import io.seata.rm.datasource.xa.DataSourceProxyXA;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

@SpringBootConfiguration
@MapperScans({
        @MapperScan(basePackages = "com.shangma.nong",sqlSessionFactoryRef = "nongFactory"),
        @MapperScan(basePackages = "com.shangma.jian",sqlSessionFactoryRef = "jianFactory")
        }
)
public class DbConfig {

    /**
     * 注册数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.nong")
    public DruidDataSource nongDataSource() {
        return new DruidDataSource();
    }
    /**
     * 手动配置农行代理数据源
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceProxy nongAT(@Qualifier("nongDataSource") DruidDataSource dataSource){
        return new DataSourceProxy(dataSource);
    }
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.jian")
    public DruidDataSource jianDatasource() {
        return new DruidDataSource();
    }
    /**
     * 手动代理建行数据源
     * @param dataSource
     * @return
     */
    @Bean
    public DataSourceProxy jianAT(@Qualifier("jianDatasource") DruidDataSource dataSource){
        return new DataSourceProxy(dataSource);
    }

    /**
     * 配置NongSqlSession
     */
    @Bean
    public SqlSessionFactory nongFactory(@Qualifier("nongAT") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 配置NongSqlSession
     */
    @Bean
    public SqlSessionFactory jianFactory(@Qualifier("jianAT") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean.getObject();
    }

}
